package com.yu.thread10;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * Created by xiaolongyu on 15/4/13.
 */
public class HorseRace {
    static final int FINISH_LINE = 75;
    private List<Horse> horses = Lists.newArrayList();
    private ExecutorService exec = Executors.newCachedThreadPool();
    private CyclicBarrier barrier;
    public HorseRace(int nHorses, final int pause){
        barrier = new CyclicBarrier(nHorses, new Runnable() {
            @Override
            public void run() {
                StringBuilder sb = new StringBuilder();
                for(int i = 0; i < FINISH_LINE; i ++){
                    sb.append("=");
                }
                System.out.print(sb);
                for(Horse h : horses){
                    System.out.print(h.tracks());
                }
                for(Horse horse : horses){
                    if(horse.getStrides() >= FINISH_LINE){
                        System.out.println(horse + " won!");
                        exec.shutdownNow();
                        return ;
                    }
                }

                try {
                    TimeUnit.MILLISECONDS.sleep(pause);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        for(int i = 0; i < nHorses; i ++){
            Horse horse = new Horse(barrier);
            horses.add(horse);
            exec.execute(horse);
        }
    }

    public static void main(String[] args) {
        int nHorses = 7;
        int pause = 200;
        new HorseRace(nHorses, pause);
    }

}

class Horse implements Runnable {

    private static int counter = 0;
    private final int id = counter ++;
    private int strides = 0;
    private static Random random = new Random(47);
    private CyclicBarrier barrier;

    public Horse(CyclicBarrier barrier){
        this.barrier = barrier;
    }

    public synchronized int getStrides(){
        return strides;
    }

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                synchronized (this) {
                    strides += random.nextInt(3);
                }
                barrier.await();
            }
        } catch (InterruptedException e){

        } catch (BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String toString() {
        return "Horse " + id + " ";
    }

    public String tracks(){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < getStrides(); i ++){
            sb.append("*");
        }
        sb.append(id);
        return sb.toString();
    }
}
